package com.example.websocket.listener;

import com.alibaba.fastjson2.JSON;
import com.example.websocket.config.ConstConfig;
import com.example.websocket.model.ChatMessage;
import com.example.websocket.service.ChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisMessageListener extends MessageListenerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisMessageListener.class);


    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private ChatService chatService;

    /**
     * 收到监听消息
     *
     * @param message
     * @param bytes
     */
    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        String rawMsg;
        String topic;
        try {
            rawMsg = redisTemplate.getValueSerializer().deserialize(body).toString();
            topic = redisTemplate.getStringSerializer().deserialize(channel);
            LOGGER.info("Received raw message from topic:" + topic + ", raw message content：" + rawMsg);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return;
        }

        ChatMessage chatMessage = JSON.parseObject(rawMsg, ChatMessage.class);
        if (chatMessage != null) {
            switch (topic) {
                case ConstConfig.MSG_TO_ALL_KEY:
                    LOGGER.info("Send message to all users:" + rawMsg);
                    chatService.sendMsg(chatMessage);
                    break;
                case ConstConfig.CHANNEL_TOPIC_KEY:
                    chatService.alertUserStatus(chatMessage);
                    break;
                default:
                    LOGGER.warn("No further operation with this topic!");
                    break;
            }
        }
    }
}
